/*-----------------------------------------------File Info------------------------------------------------
** File Name:               BleModule.c  
** Last modified date:      2016.07.22
** Last version:            V0.1
** Description:             
**--------------------------------------------------------------------------------------------------------            
** Created date:            2016.09.07
** author:                  YLY
** Version:                 V0.1
** Descriptions:            蓝牙模块 
**--------------------------------------------------------------------------------------------------------
*/

/*************************************************************
* 	include 
* 	头文件	
*************************************************************/
/*   硬件库文件     */

#include "BleModule.h"
#include "arithmetic.h"
#include "wirelessModule.h"
#include "userTask.h"



uint8_t ucgBleTaskId;

tsBle tBle;
static void enterAtMode(uint32_t eventId, uint32_t param);
static void atModeTimeout(uint32_t eventId, uint32_t param);

/*
#define U0_READY		GPIOA,GPIO_PIN_4		//PA4
#define U0_RST			GPIOA,GPIO_PIN_5		//PA5
*/
/**
*	function:	
*	作用:	起动时检查BLE参数配置,
			因为用到DATA_FLASH,
			必需在读取数据后才能初始化
*	return :	no
*	返回:	
**/
void initBle(void)
{
	gpio_bit_write(U0_READY, 1);/* 先退出AT模式 */
	if(ptgUserData->userMark != USER_DATA_MARK)
	{
		BLE_PRINTF("BLEStartupChecErr\r\n");
		return;
	}
	if(ptgUserData->wifiOrBleInitFlg && 
	  (ptgUserData->wifiOrBleInitCount < 3))
	{	
		tBle.setTimes	= 0;				/* 本次初始化模块次数 */
		createEvent(3000,enterAtMode,0);
	}	
	else
	{	
		enableBeat();
		tBle.bleWorkMode = THROUGH_MODE;
		tBle.bleSetStatus = IDLE;
	}		
}

//extern void fmcErasePages(uint32_t address, uint16_t pageNum);
//extern void fmcProgram(uint32_t address, uint8_t *pData, uint16_t dataNum);
/**
*	function:	
*	作用:	 设置BLE模块参数
*	return :	no
*	返回:	
**/
void setBleParameter(void)
{	
	tsUserData *p;
	
	p = (tsUserData *)osMalloc(sizeof(tsUserData));
	if(p == NULL)
		return;
	memcpy((void *)p, (void *)ptgUserData, sizeof(tsUserData));
		
	p->wifiOrBleInitFlg = 1;
	p->wifiOrBleInitCount = 0;
	
	fmcErasePages(USER_DATA_ADDR,1);										/* 擦除FLASH */
	fmcProgram(USER_DATA_ADDR,(uint8_t *)p,sizeof(tsUserData));				/* 保存数据 */	
	
	osFree(p);
	
	tBle.setTimes	= 0;				/* 本次初始化模块次数 */
}



/**
*	function:	使BLE进入AT
*	作用:	 
*	return :	no
*	返回:	
**/

static void repeatSetBleEvent(uint32_t eventId, uint32_t param)
{	
	enterAtMode(0, 0);	
}

/**
*	function:	使BLE进入AT
*	作用:	 
*	return :	no
*	返回:	
**/
static void enterAtMode(uint32_t eventId, uint32_t param)
{
	buzzerStart(5,1);	
	BLE_PRINTF("bleEnterAT\r\n");
	
	//disableBeat();							/* AT模式下关闭心跳 */
	tBle.bleWorkMode = AT_MODE;			/* BLE工作模式 */
	tBle.bleSetStatus = WAIT_ENTER_AT;	/* 等待收到模块应答,进入AT模式 */	
	createEvent(5000,atModeTimeout,0);		/* 5S钟BLE无应答超时退出 */	
	gpio_bit_write(U0_READY, 0);	/* 拉P23口使BLE进入AT模式 */	
}

/**
*	function:	退出AT,
*	作用:	
*	uint8_t ucRepeatInit: 0,停止初始化,1重新初始化
*	return :	no
*	返回:	
**/
static void exitAtMode(uint8_t ucRepeatInit)
{
	tsUserData *p;
	
	gpio_bit_write(U0_READY, 1);	/* 退出AT模式 */
	enableBeat();		/* 打开心跳 */
	tBle.bleSetStatus = IDLE;
	tBle.bleWorkMode = THROUGH_MODE;
	if(ucRepeatInit)
	{	
		if(++tBle.setTimes >= BLE_INIT_MAX_TIMES)
		{	
			p = (tsUserData *)osMalloc(sizeof(tsUserData));
			if(p == NULL)
				return;
			memcpy((void *)p, (void *)ptgUserData, sizeof(tsUserData));
				
			p->wifiOrBleInitCount++;		/* 重置模块上电初始化设置标识,当模块初始化3次均失败,下次开机再次初始化 */
			
			fmcErasePages(USER_DATA_ADDR,1);										/* 擦除FLASH */
			fmcProgram(USER_DATA_ADDR,(uint8_t *)p,sizeof(tsUserData));				/* 保存数据 */	
			
			osFree(p);
			
			buzzerStart(10,2);
			return;
		}
		createEvent(3000, repeatSetBleEvent, 0);/* 3S后重新设置BLE */
	}
	else
	{
		p = (tsUserData *)osMalloc(sizeof(tsUserData));
		if(p == NULL)
			return;
		memcpy((void *)p, (void *)ptgUserData, sizeof(tsUserData));
		p->wifiOrBleInitCount=0;;		/* 重置模块上电初始化设置标识,当模块初始化3次均失败,下次开机再次初始化 */
		p->wifiOrBleInitFlg = 0;			
		
		fmcErasePages(USER_DATA_ADDR,1);										/* 擦除FLASH */
		fmcProgram(USER_DATA_ADDR,(uint8_t *)p,sizeof(tsUserData));				/* 保存数据 */	
		
		osFree(p);
		
		cleanEvent(atModeTimeout);
		buzzerStart(50,3);
	}
	BLE_PRINTF("bleExitAT\r\n");
}

/**
*	function:	AT模式超时
*	作用:	 
*	return :	no
*	返回:	
**/
static void atModeTimeout(uint32_t eventId, uint32_t param)
{
	exitAtMode(1);	
}


/**
*	function:	BLE参数配置
*	作用:	 
*	return :	no
*	返回:	
**/	
void setBleHandle(char *pRece, char *pName, uint8_t *pDeviceId, uint8_t deviceType)
{
	uint8_t sendBuf[64];	
	uint64_t deviceId=0;
	int i;
	tsUserData *p;
	
	switch(tBle.bleSetStatus)
	{	
		/* 等待进入AT模式,并关闭回显 */
		case WAIT_ENTER_AT:	
		{
			BLE_INFO("Rece=%s",pRece);			
			if(strstr(pRece, "ENAT\r"))	/* 进入AT模式 */
			{
				createEvent(5000,atModeTimeout,0);	/* 3S钟BLE无应答超时退出 */	
				memset(sendBuf,0x00,sizeof(sendBuf));
				sprintf((char *)sendBuf,"AT+E\r");				/* 关闭回显 */
				
				BLE_INFO("Send=%s",(char *)sendBuf);	
									
				uartWrite(MODULE_UART, sendBuf, strlen((char *)sendBuf));
				tBle.bleSetStatus = WAIT_CLOSE_ECHO;
			}
			else if(strstr(pRece, "DNAT\r"))	/* 退出AT模式 */
			{
				exitAtMode(1);  /* 异常退出重新初始化 */
			}			
		}break;
		
		/* 等待关闭回显,并设置名称 */			
		case WAIT_CLOSE_ECHO:
		{
			BLE_INFO("Rece=%s",pRece);	
			if(strstr(pRece, "OK->\r"))	/* 已经关闭回显 */
			{
				createEvent(5000,atModeTimeout,0);	/* 3S钟BLE无应答超时退出 */	
				memset(sendBuf,0x00,sizeof(sendBuf));
				sprintf((char *)sendBuf,"AT+REN-%s\r",pName);	
				
				BLE_INFO("Send=%s",(char *)sendBuf);	
				uartWrite(MODULE_UART, sendBuf, strlen((char *)sendBuf));					
				tBle.bleSetStatus = WAIT_SET_NAME;
			}
			else if(strstr(pRece, "DNAT\r"))	/* 退出AT模式 */
			{
				exitAtMode(1);
			}			
		}break;	
			
		/* 等待设置名称,设置设备ID */			
		case WAIT_SET_NAME:
		{
			BLE_INFO("Rece=%s",pRece);	
			if(strstr(pRece, "OK->\r"))	/* 名称设置成功 */
			{
				createEvent(5000,atModeTimeout,0);	/* 3S钟BLE无应答超时退出 */	
				memset(sendBuf,0x00,sizeof(sendBuf));
				
//				uiDeviceId = ((uint32_t)pDeviceId[0]<<24) + ((uint32_t)pDeviceId[1]<<16) + ((uint32_t)pDeviceId[2]<<8) + ((uint32_t)pDeviceId[3]);
//				sprintf((char *)sendBuf, "AT+SID-%d.%d\r",ucDeviceType,uiDeviceId);				
				
				deviceId = 0;
				for(i=0;i<4;i++)
				{				
					deviceId |= (uint64_t)pDeviceId[i] << ((3-i)*8);			
				}				
				if(sizeof(ptgUserData->hostPid) == 8)
				{
					for(i=0;i<4;i++)			
						deviceId |= (uint64_t)pDeviceId[i+4] << ((7-i)*8);			
				}	
				sprintf((char *)sendBuf, "AT+SID-%u.%llu\r",deviceType,deviceId);	
				
				BLE_INFO("Send=%s",(char *)sendBuf);	
				uartWrite(MODULE_UART, sendBuf, strlen((char *)sendBuf));									
				tBle.bleSetStatus = WAIT_SET_TYPE_ID;
			}
			else if(strstr(pRece, "DNAT\r"))	/* 退出AT模式 */
			{
				exitAtMode(1);
			}			
		}break;                                                      
			
		/* 设置设备ID成功,重启模块 */			
		case WAIT_SET_TYPE_ID:
		{
			BLE_INFO("Rece=%s",pRece);	
			if(strstr(pRece, "OK->\r"))	/* ID设置成功 */
			{
				createEvent(5000, atModeTimeout, 0);	/* 3S钟BLE无应答超时退出 */	
				memset(sendBuf,0x00,sizeof(sendBuf));
				sprintf((char *)sendBuf, "AT+RST\r");	/* 重启模块 */
				
				BLE_INFO("Send=%s",(char *)sendBuf);	
														
				uartWrite(MODULE_UART, sendBuf, strlen((char *)sendBuf));
				exitAtMode(0);		/* 正常退出不再初始化 */

				p = (tsUserData *)osMalloc(sizeof(tsUserData));
				if(p == NULL)
					return;
				memcpy((void *)p, (void *)ptgUserData, sizeof(tsUserData));
				p->wifiOrBleInitCount=0xff;;		/* 标识BLE已初始化 */			
				
				fmcErasePages(USER_DATA_ADDR,1);										/* 擦除FLASH */
				fmcProgram(USER_DATA_ADDR,(uint8_t *)p,sizeof(tsUserData));				/* 保存数据 */	
				
				osFree(p);

			}
			else if(strstr(pRece, "DNAT\r"))	/* 退出AT模式 */
			{
				exitAtMode(1);	
			}			
		}break;
				
		default:
		break;			
	}
}

